public class _线程交替执行 {
    private static int count = 4;

    private static final Object lock = new Object();

    public static Boolean flag = true;

    /*public static void main(String[] args) {
        Runnable runnable = () -> {
            for (int i = 0; i <= 100; i++) {
                System.out.println(Thread.currentThread().getName() + "-----" + i);
                if (i % 20 == 0) {
                    Thread.yield();
                }
            }
        };
        new Thread(runnable, "栈长").start();
        new Thread(runnable, "小蜜").start();
    }*/

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    while (count >= 0){
                        if(count % 2 == 1){
                            System.out.print("A");
                            count--;
                            lock.notifyAll();
                        }
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }).start();
        new Thread(new Runnable(){
            @Override
            public void run(){
                synchronized (lock){
                    while(count >= 0){
                        if(count % 2 == 0 && flag == true){
                            System.out.print("B");
                            count--;
                            flag = false;
                            lock.notifyAll();
                        }
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }

            }
        }).start();
        new Thread(new Runnable(){
            @Override
            public void run(){
                synchronized (lock){
                    while (count >= 0){
                        if(count % 2 == 0 && flag == false){
                            System.out.print("C");
                            count--;
                            flag = true;
                            lock.notifyAll();
                        }
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }

            }
        }).start();
    }

}
